package com.tensai.core.interceptor;

import com.tensai.core.constant.HttpProtocol;
import com.tensai.core.constant.ServletPathNoSessionAccess;
import com.tensai.core.constant.UndefinedField;
import com.tensai.core.mvc.base.tools.SessionInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限拦截器(拦截除系统管理员以外的用户登录操作)
 *
 * @author kissy
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

//	private static ApplicationContext ctx = null;

    /**
     * preHandle在业务处理器处理请求之前被调用。预处理，可以进行编码、安全控制等处理；
     *
     * @param request  请求
     * @param response 请求
     * @param handler  句柄
     * @return 布尔
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.addHeader(HttpProtocol.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        response.addHeader(HttpProtocol.ACCESS_CONTROL_ALLOW_METHODS, "POST,GET");
        for (ServletPathNoSessionAccess servletPath : ServletPathNoSessionAccess.values()) {
            if (request.getServletPath().contains(servletPath.getValue())) {
                return true;
            }
        }
        String xRequestWith = request.getHeader(HttpProtocol.X_REQUESTED_WITH);
        if (StringUtils.isNotEmpty(xRequestWith) && xRequestWith.contains(HttpProtocol.XML_HTTP_REQUEST)) {
            //ajax请求暂时直接不过滤
            return true;
        }

        SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute("sessionInfo");
        // admin用户不需要验证权限
        if (UndefinedField.ADMIN_UUID == sessionInfo.getUserId()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * postHandle在业务处理器处理请求执行完成后，生成视图之前执行。后处理（调用了Service并返回ModelAndView，但未进行页面渲染），
     * 有机会修改ModelAndView；
     *
     * @param request       请求
     * @param response      响应
     * @param handler       句柄
     * @param modelAndView  视图
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

}
